<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>售票功能 - 电影院管理系统</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background-color: #f5f5f5;
            line-height: 1.6;
        }
        
        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 1rem 0;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .nav {
            max-width: 1200px;
            margin: 0 auto;
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0 20px;
        }
        
        .logo {
            font-size: 24px;
            font-weight: bold;
        }
        
        .nav-links {
            display: flex;
            gap: 30px;
        }
        
        .nav-links a {
            color: white;
            text-decoration: none;
            font-weight: 500;
            transition: opacity 0.3s;
        }
        
        .nav-links a:hover {
            opacity: 0.8;
        }
        
        .user-info {
            display: flex;
            align-items: center;
            gap: 15px;
        }
        
        .container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 30px 20px;
        }
        
        .btn {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 10px;
            cursor: pointer;
            text-decoration: none;
            display: inline-block;
            font-size: 14px;
            font-weight: 600;
            transition: all 0.3s ease;
            box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
        }
        
        .btn:hover {
            transform: translateY(-3px);
            box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
        }

        .btn-sm {
            padding: 6px 12px;
            font-size: 12px;
        }
        
        .management-section {
            background: white;
            padding: 25px;
            border-radius: 20px;
            box-shadow: 0 8px 25px rgba(0,0,0,0.08);
            margin-bottom: 25px;
            border: 1px solid #f0f0f0;
            transition: all 0.3s ease;
        }
        
        .management-section:hover {
            box-shadow: 0 12px 35px rgba(0,0,0,0.12);
            transform: translateY(-3px);
        }
        
        .section-title {
            font-size: 24px;
            color: #333;
            margin-bottom: 20px;
            border-bottom: 3px solid #667eea;
            padding-bottom: 10px;
        }
        
        .form-label {
            font-weight: 600;
            color: #333;
            margin-bottom: 8px;
            display: block;
        }
        
        .form-select, .form-control {
            width: 100%;
            padding: 12px;
            border: 2px solid #e1e5e9;
            border-radius: 10px;
            font-size: 14px;
            transition: border-color 0.3s;
            box-shadow: inset 0 1px 3px rgba(0,0,0,0.1);
        }
        
        .form-select:focus, .form-control:focus {
            outline: none;
            border-color: #667eea;
        }
        
        .row {
            display: flex;
            gap: 30px;
            margin-bottom: 30px;
            flex-wrap: wrap;
        }
        
        .col-md-4 {
            flex: 1;
        }
        
        .seat {
            width: 40px;
            height: 40px;
            margin: 3px;
            border: none;
            border-radius: 8px;
            font-size: 14px;
            font-weight: bold;
            transition: all 0.3s ease;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }
        .seat:hover:not(:disabled) {
            transform: scale(1.1);
        }
        .seat-available {
            background: linear-gradient(135deg, #e9ecef 0%, #d1d1d1 100%);
            color: #495057;
            border: 1px solid #ced4da;
            position: relative;
            overflow: hidden;
        }
        .seat-available:hover {
            background: linear-gradient(135deg, #28a745 0%, #208a3a 100%);
            color: white;
            transform: scale(1.05);
        }
        .seat-selected {
            background: linear-gradient(135deg, #28a745 0%, #208a3a 100%);
            color: white;
            transform: scale(1.05);
            box-shadow: 0 4px 10px rgba(40, 167, 69, 0.4);
        }
        .seat-occupied {
            background: linear-gradient(135deg, #dc3545 0%, #bd2130 100%);
            color: white;
            cursor: not-allowed;
            opacity: 0.7;
        }
        .seat-maintenance {
            background: linear-gradient(135deg, #ffc107 0%, #e0a800 100%);
            color: #212529;
            cursor: not-allowed;
            opacity: 0.7;
        }
        .screen {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 25px;
            border-radius: 20px;
            margin: 30px auto;
            width: 60%;
            max-width: 500px;
            text-align: center;
            box-shadow: 0 8px 25px rgba(102, 126, 234, 0.4);
            font-size: 20px;
            font-weight: bold;
            letter-spacing: 2px;
            position: relative;
            overflow: hidden;
        }
        .screen:before {
            content: '';
            position: absolute;
            top: -50%;
            left: -50%;
            width: 200%;
            height: 200%;
            background: radial-gradient(circle, rgba(255,255,255,0.3) 0%, rgba(255,255,255,0) 70%);
            transform: rotate(30deg);
        }
        .seat-map {
            max-width: 100%;
            margin: 0 auto;
            padding: 30px;
            background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
            border-radius: 20px;
            box-shadow: 0 6px 20px rgba(0,0,0,0.08);
            border: 1px solid #e9ecef;
            text-align: center;
        }
        .row-label {
            width: 30px;
            display: inline-block;
            text-align: center;
            font-weight: bold;
            color: #6c757d;
        }
        .ticket-summary {
            position: sticky;
            top: 30px;
        }
        .alert-success {
            border-left: 4px solid #28a745;
        }
        .alert-error {
            border-left: 4px solid #dc3545;
        }
        
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
        }
        
        .modal-content {
            background-color: white;
            margin: 5% auto;
            padding: 20px;
            border-radius: 15px;
            width: 90%;
            max-width: 500px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.3);
        }
        
        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 2px solid #f0f0f0;
        }
        
        .close {
            background: none;
            border: none;
            font-size: 24px;
            cursor: pointer;
            color: #999;
        }
        
        .close:hover {
            color: #333;
        }
    </style>
</head>
<body>
    <header class="header">
        <nav class="nav">
            <div class="logo">🎬 前台控制台</div>
            <div class="nav-links">
                <a href="/receptionist/dashboard">控制台</a>
                <a href="/receptionist/movies">影片信息</a>
                <a href="/receptionist/screenings">场次信息</a>
                <a href="/receptionist/sell-ticket">售票功能</a>
                <a href="/receptionist/refund-ticket">退票功能</a>
                <a href="/receptionist/sold-tickets">已售票据</a>
            </div>
            <div class="user-info">
                <span th:text="|前台：${session.user != null ? session.user.username : '未登录'}|">前台</span>
                <a href="/auth/logout" class="btn btn-sm">退出登录</a>
            </div>
        </nav>
    </header>

    <div class="container">
        <!-- 消息提示 -->
        <div th:if="${success}" class="alert alert-success alert-dismissible fade show" role="alert">
            <i class="fas fa-check-circle me-2"></i>
            <span th:text="${success}"></span>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
        
        <div th:if="${error}" class="alert alert-danger alert-dismissible fade show" role="alert">
            <i class="fas fa-exclamation-triangle me-2"></i>
            <span th:text="${error}"></span>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>

        <!-- 场次选择 -->
        <div class="management-section">
            <h2 class="section-title">🎫 售票系统</h2>
            
            <form id="screeningForm">
                <div class="row">
                    <div class="col-md-4">
                        <label class="form-label">选择影片</label>
                        <select class="form-select" name="movieId" id="movieSelect" onchange="loadMovieScreenings()">
                            <option value="">请选择影片</option>
                            <option th:each="movie : ${movies}" 
                                    th:value="${movie.id}" 
                                    th:text="${movie.title}">
                            </option>
                        </select>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">选择场次</label>
                        <select class="form-select" name="screeningId" id="screeningSelect" disabled onchange="loadScreeningDetails()">
                            <option value="">请先选择影片</option>
                        </select>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">&nbsp;</label>
                        <button type="button" class="btn" onclick="loadSeatMap()" id="loadSeatsBtn" disabled>
                            进入选座
                        </button>
                    </div>
                </div>
            </form>
        </div>

        <!-- 售票界面 -->
        <div id="ticketingInterface" style="display: none;">
            <div class="row" style="display: flex; flex-wrap: wrap; gap: 20px;">
                <!-- 左侧：场次信息和座位图 -->
                <div class="ticketing-left-container" style="flex: 1; min-width: 65%; max-width: 70%;">
                    <!-- 场次信息 -->
                    <div class="management-section">
                        <h3 class="section-title">🎬 场次信息</h3>
                        <div id="screeningInfo" class="p-3">
                            <div class="text-muted text-center py-3">
                                <i class="fas fa-film fa-2x mb-2"></i>
                                <div>请先选择场次</div>
                            </div>
                        </div>
                    </div>

                    <!-- 座位图 -->
                    <div class="management-section">
                        <h3 class="section-title">🪑 选择座位</h3>
                        
                        <!-- 座位图例 -->
                        <div style="text-align: center; margin-bottom: 20px;">
                            <div style="display: flex; justify-content: center; gap: 20px; flex-wrap: wrap;">
                                <div style="display: flex; align-items: center; gap: 8px;">
                                    <button class="seat seat-available" disabled></button>
                                    <small>可选</small>
                                </div>
                                <div style="display: flex; align-items: center; gap: 8px;">
                                    <button class="seat seat-selected" disabled></button>
                                    <small>已选</small>
                                </div>
                                <div style="display: flex; align-items: center; gap: 8px;">
                                    <button class="seat seat-occupied" disabled></button>
                                    <small>已售</small>
                                </div>
                            </div>
                        </div>

                        <!-- 屏幕 -->
                        <div class="screen">
                            🎬 屏幕
                        </div>

                        <!-- 座位地图 -->
                        <div class="seat-map" id="seatMap">
                            <div style="text-align: center; color: #999; padding: 30px;">
                                <div style="font-size: 48px; margin-bottom: 15px;">👆</div>
                                <div>请先选择场次</div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 右侧：票务信息和结算 -->
                <div style="width: 30%; min-width: 300px;">
                    <div class="ticket-summary">
                        <!-- 已选座位 -->
                        <div class="management-section">
                            <h3 class="section-title">📝 已选座位 <span style="background: #667eea; color: white; padding: 4px 8px; border-radius: 12px; font-size: 12px; margin-left: 50px;" id="selectedCount">0</span></h3>
                            
                            <div id="selectedSeats" style="margin-bottom: 20px; max-height: 200px; overflow-y: auto; display: flex; flex-wrap: wrap; gap: 8px;">
                                <div style="text-align: center; color: #999; padding: 30px; width: 100%;">
                                    <div style="font-size: 48px; margin-bottom: 15px;">👆</div>
                                    <div>请在左侧选择座位</div>
                                </div>
                            </div>
                            
                            <!-- 票型选择 -->
                            <div style="margin-bottom: 20px;">
                                <label class="form-label">票型选择</label>
                                <div style="margin-bottom: 10px;">
                                    <input type="radio" name="ticketType" id="adultTicket" value="false" checked onchange="updatePricing()" style="margin-right: 8px;">
                                    <label for="adultTicket">成人票 (原价)</label>
                                </div>
                                <div>
                                    <input type="radio" name="ticketType" id="childTicket" value="true" onchange="updatePricing()" style="margin-right: 8px;">
                                    <label for="childTicket">儿童票 (8折)</label>
                                </div>
                            </div>

                            <!-- 折扣设置 -->
                            <div style="margin-bottom: 20px;">
                                <label class="form-label">折扣 (1.0 = 无折扣)</label>
                                <input type="number" class="form-control" id="discountInput" value="1.0" min="0.1" max="1.0" step="0.1" onchange="updatePricing()">
                            </div>
                        </div>

                        <!-- 价格明细 -->
                        <div class="management-section">
                            <h3 class="section-title">💰 价格明细</h3>
                            
                            <div style="display: flex; justify-content: space-between; margin-bottom: 10px;">
                                <span>单价：</span>
                                <span>¥<span id="unitPrice">0</span></span>
                            </div>
                            <div style="display: flex; justify-content: space-between; margin-bottom: 10px;">
                                <span>数量：</span>
                                <span id="ticketCount">0</span>
                            </div>
                            <div style="display: flex; justify-content: space-between; margin-bottom: 10px;">
                                <span>已享折扣：</span>
                                <span>¥<span id="discountAmount">0</span></span>
                            </div>
                            <hr style="border-color: #e1e5e9;">
                            <div style="display: flex; justify-content: space-between; font-weight: bold; color: #28a745; font-size: 18px;">
                                <span>总计：</span>
                                <span>¥<span id="totalAmount">0</span></span>
                            </div>
                        </div>

                        <!-- 确认购买 -->
                        <div class="management-section">
                            <button type="button" class="btn" style="width: 100%; font-size: 16px; padding: 15px;" id="confirmPurchase" disabled onclick="confirmPurchase()">
                                💳 确认购买
                            </button>
                            <div style="text-align: center; margin-top: 10px;">
                                <small style="color: #999;">请确认座位选择后点击购买</small>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 确认购买模态框 -->
    <div class="modal" id="purchaseModal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 style="margin: 0;">🛒 确认购买</h3>
                <button type="button" class="close" onclick="closeModal('purchaseModal')">&times;</button>
            </div>
            <div style="margin: 20px 0;">
                <h6>购票信息确认</h6>
                <div style="background: #f8f9fa; padding: 15px; border-radius: 8px; margin: 15px 0;" id="confirmTable">
                    <!-- 确认信息将通过JavaScript动态填充 -->
                </div>
                <div style="background: #fff3cd; border: 1px solid #ffeaa7; padding: 15px; border-radius: 8px; color: #856404;">
                    ⚠️ 请确认购票信息无误，购买后将生成电子票据。
                </div>
            </div>
            <div style="display: flex; gap: 10px; justify-content: center; margin-top: 20px;">
                <button type="button" class="btn" onclick="closeModal('purchaseModal')" style="background: #6c757d;">取消</button>
                <button type="button" class="btn btn-success" onclick="processPurchase()" style="background: #28a745;">✅ 确认支付</button>
            </div>
        </div>
    </div>

    <!-- 购买成功模态框 -->
    <div class="modal" id="successModal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 style="color: #28a745; margin: 0;">✅ 购票成功</h3>
                <button type="button" class="close" onclick="closeModal('successModal')">&times;</button>
            </div>
            <div style="text-align: center; margin: 20px 0;">
                <div style="font-size: 64px; color: #28a745; margin-bottom: 20px;">🎫</div>
                <h6>电影票购买成功！</h6>
            </div>
            <div style="background: #f8f9fa; padding: 20px; border-radius: 8px; margin: 20px 0;">
                <div style="display: flex; justify-content: space-between; margin-bottom: 10px;">
                    <strong>订单号:</strong>
                    <span id="successOrderId"></span>
                </div>
                <div id="ticketNumbersContainer" style="display: none; justify-content: space-between; margin-bottom: 10px;">
                    <strong>电子票号:</strong>
                    <span id="successTicketNumbers"></span>
                </div>
                <div style="display: flex; justify-content: space-between; margin-bottom: 10px;">
                    <strong>影片:</strong>
                    <span id="successMovieTitle"></span>
                </div>
                <div style="display: flex; justify-content: space-between; margin-bottom: 10px;">
                    <strong>场次:</strong>
                    <span id="successScreeningTime"></span>
                </div>
                <div style="display: flex; justify-content: space-between; margin-bottom: 10px;">
                    <strong>座位:</strong>
                    <span id="successSeats"></span>
                </div>
                <div style="display: flex; justify-content: space-between; margin-bottom: 10px;">
                    <strong>总金额:</strong>
                    <span style="color: #28a745; font-weight: bold;" id="successTotalAmount"></span>
                </div>
            </div>
            <div style="display: flex; gap: 10px; justify-content: center; margin-top: 20px;">
                <button type="button" class="btn" onclick="resetForm(); closeModal('successModal');">🎫 继续售票</button>
            </div>
        </div>
    </div>

    <script>
        let currentScreening = null;
        let selectedSeats = [];
        let soldSeats = [];
        let basePrice = 0;
        
        // 加载影片的场次
        function loadMovieScreenings() {
            const movieId = document.getElementById('movieSelect').value;
            const screeningSelect = document.getElementById('screeningSelect');
            const loadSeatsBtn = document.getElementById('loadSeatsBtn');
            
            if (!movieId) {
                screeningSelect.innerHTML = '<option value="">请先选择影片</option>';
                screeningSelect.disabled = true;
                loadSeatsBtn.disabled = true;
                return;
            }
            
            fetch(`/receptionist/movie-screenings?movieId=${movieId}`)
                .then(response => {
                    // 检查响应是否为JSON格式
                    const contentType = response.headers.get('content-type');
                    if (!contentType || !contentType.includes('application/json')) {
                        throw new Error('未获取到JSON响应，可能会话已过期');
                    }
                    return response.json();
                })
                .then(data => {
                    screeningSelect.innerHTML = '<option value="">请选择场次</option>';
                    
                    // 检查是否是错误响应
                    if (data.success === false) {
                        screeningSelect.innerHTML = '<option value="">权限不足，请重新登录</option>';
                        alert(data.message || '权限不足，请重新登录');
                        window.location.href = '/login';
                        return;
                    }
                    
                    // 正常处理场次数据
                    const screenings = Array.isArray(data) ? data : [];
                    if (screenings.length === 0) {
                        screeningSelect.innerHTML = '<option value="">该影片暂无可用场次</option>';
                    } else {
                        screenings.forEach(screening => {
                            const option = document.createElement('option');
                            option.value = screening.id;
                            const startTime = new Date(screening.startTime).toLocaleString('zh-CN');
                            option.textContent = `${startTime} - ${screening.roomName} - ¥${screening.price}`;
                            screeningSelect.appendChild(option);
                        });
                    }
                    
                    screeningSelect.disabled = false;
                    loadSeatsBtn.disabled = false;
                })
                .catch(error => {
                    console.error('Error:', error);
                    if (error.message.includes('未获取到JSON响应')) {
                        alert('会话已过期，请重新登录');
                    } else {
                        screeningSelect.innerHTML = '<option value="">加载失败</option>';
                    }
                });
        }
        
        

        // 加载场次详情
        function loadScreeningDetails() {
            const screeningId = document.getElementById('screeningSelect').value;
            const loadSeatsBtn = document.getElementById('loadSeatsBtn');
            
            if (screeningId) {
                loadSeatsBtn.disabled = false;
            } else {
                loadSeatsBtn.disabled = true;
            }
        }
        
        // 加载座位图
        function loadSeatMap() {
            const screeningId = document.getElementById('screeningSelect').value;
            if (!screeningId) {
                alert('请先选择场次');
                return;
            }
            
            // 显示售票界面
            document.getElementById('ticketingInterface').style.display = 'block';
            
            // 获取场次详情和座位数据
            fetch(`/receptionist/screening-seats?screeningId=${screeningId}`)
                .then(response => {
                    // 检查响应是否为JSON格式
                    const contentType = response.headers.get('content-type');
                    if (!contentType || !contentType.includes('application/json')) {
                        throw new Error('未获取到JSON响应，可能会话已过期');
                    }
                    return response.json();
                })
                .then(data => {
                    // 检查是否是错误响应
                    if (data.success === false) {
                        alert(data.message || '获取座位信息失败');
                        return;
                    }
                    
                    currentScreening = data.screening;
                    basePrice = parseFloat(data.screening.price);
                    
                    // 显示场次信息
                    const startTime = new Date(data.screening.startTime).toLocaleString('zh-CN');
                    document.getElementById('screeningInfo').innerHTML = `
                        <div class="row">
                            <div class="col-md-3">
                                <strong>影片名称</strong>
                                <div class="text-primary">${data.screening.movie.title}</div>
                            </div>
                            <div class="col-md-3">
                                <strong>放映厅</strong>
                                <div>${data.screening.room.name}</div>
                            </div>
                            <div class="col-md-3">
                                <strong>放映时间</strong>
                                <div>${startTime}</div>
                            </div>
                            <div class="col-md-3">
                                <strong>票价</strong>
                                <div class="text-success fw-bold">¥${data.screening.price}</div>
                            </div>
                        </div>
                    `;
                    
                    // 设置已售座位
                    soldSeats = data.occupiedSeats || [];
                    
                    // 生成座位图
                    generateSeatMap(data.totalSeats);
                    updatePricing();
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('加载座位信息失败');
                });
        }
        
        // 生成座位图
        function generateSeatMap(totalSeats) {
            const seatMapDiv = document.getElementById('seatMap');
            let html = '';
            
            // 检查是否有座位数据
            if (!totalSeats || totalSeats <= 0) {
                seatMapDiv.innerHTML = '<div class="alert alert-warning text-center py-3"><i class="fas fa-exclamation-triangle me-2"></i>该场次暂无座位数据</div>';
                return;
            }
            
            const rows = Math.ceil(totalSeats / 10); // 假设每排10个座位
            const seatsPerRow = Math.ceil(totalSeats / rows);
            
            for (let row = 1; row <= rows; row++) {
                html += '<div class="mb-2 text-center" style="display: flex; justify-content: center; align-items: center;">';
                html += '<span class="row-label">' + String.fromCharCode(64 + row) + '</span>';
                
                for (let seat = 1; seat <= seatsPerRow; seat++) {
                    const seatNumber = (row - 1) * seatsPerRow + seat;
                    if (seatNumber <= totalSeats) {
                        const seatId = `${String.fromCharCode(64 + row)}-${seat}`;
                        
                        // 检查座位是否被占用（支持不同格式的座位编号）
                        const isOccupied = soldSeats.some(occupied => {
                            if (typeof occupied === 'string') {
                                return occupied === seatId;
                            } else {
                                return occupied === seatNumber;
                            }
                        });
                        
                        let seatClass = 'seat seat-available';
                        let disabled = '';
                        
                        if (isOccupied) {
                            seatClass = 'seat seat-occupied';
                            disabled = 'disabled';
                        }
                        
                        html += `<button type="button" class="${seatClass}" id="seat-${seatId}" data-seat-id="${seatId}" ${disabled} onclick="toggleSeat('${seatId}')">`;
                         html += `${String.fromCharCode(64 + row)}${seat}`;
                         html += '</button>';
                    }
                }
                html += '</div>';
            }
            
            seatMapDiv.innerHTML = html;
        }
        
        // 切换座位选择状态
        function toggleSeat(seatId) {
            const seatButton = document.getElementById('seat-' + seatId);
            const seatIndex = selectedSeats.indexOf(seatId);
            
            if (seatIndex > -1) {
                // 取消选择
                selectedSeats.splice(seatIndex, 1);
                seatButton.className = 'seat seat-available';
            } else {
                // 选择座位
                selectedSeats.push(seatId);
                seatButton.className = 'seat seat-selected';
            }
            
            updateSelectedSeatsDisplay();
            updatePricing();
        }
        
        // 更新已选座位显示
        function updateSelectedSeatsDisplay() {
            const selectedSeatsDiv = document.getElementById('selectedSeats');
            const selectedCountSpan = document.getElementById('selectedCount');
            
            selectedCountSpan.textContent = selectedSeats.length;
            
            if (selectedSeats.length === 0) {
                selectedSeatsDiv.innerHTML = '<div class="text-muted text-center py-3" style="width: 100%;"><i class="fas fa-hand-pointer fa-2x mb-2"></i><div>请在左侧选择座位</div></div>';
                document.getElementById('confirmPurchase').disabled = true;
            } else {
                let html = '';
                selectedSeats.forEach(seatId => {
                    html += `<span style="background: #28a745; color: white; padding: 8px 12px; border-radius: 8px; display: inline-block; font-weight: bold;">${seatId}</span>`;
                });
                selectedSeatsDiv.innerHTML = html;
                document.getElementById('confirmPurchase').disabled = false;
            }
        }
        
        // 更新价格计算
        function updatePricing() {
            const isChildTicket = document.querySelector('input[name="ticketType"]:checked').value === 'true';
            const discount = parseFloat(document.getElementById('discountInput').value);
            const count = selectedSeats.length;
            
            // 计算最终折扣
            let finalDiscount = discount;
            if (isChildTicket) {
                finalDiscount *= 0.8; // 儿童票8折
            }
            
            // 计算单价和总价
            const originalUnitPrice = basePrice;
            const unitPrice = Math.round(basePrice * finalDiscount * 100) / 100;
            const discountAmount = Math.round((basePrice - unitPrice) * count * 100) / 100;
            const totalAmount = Math.round(unitPrice * count * 100) / 100;
            // 更新显示
            document.getElementById('unitPrice').textContent = unitPrice.toFixed(2);
            document.getElementById('ticketCount').textContent = count;
            document.getElementById('totalAmount').textContent = totalAmount.toFixed(2);
            document.getElementById('discountAmount').textContent = discountAmount.toFixed(2);
        }
        
        // 确认购买
        function confirmPurchase() {
            if (selectedSeats.length === 0) {
                showAlert('请先选择座位', 'warning');
                return;
            }
            
            const screeningSelect = document.getElementById('screeningSelect');
            if (!screeningSelect.value) {
                showAlert('请选择场次', 'warning');
                return;
            }
            
            const isChildTicket = document.querySelector('input[name="ticketType"]:checked').value === 'true';
            const ticketTypeName = isChildTicket ? '儿童票 (8折)' : '成人票 (原价)';
            const totalAmount = document.getElementById('totalAmount').textContent;
            
            // 填充确认信息
            let seatNames = selectedSeats.map(seatId => {
                const [row, seat] = seatId.split('-');
                const rowLetter = String.fromCharCode(64 + parseInt(row));
                return `${rowLetter}排${seat}座`;
            }).join(', ');
            
            const screeningInfo = document.getElementById('screeningInfo');
            const movieTitle = screeningInfo.querySelector('.text-primary').textContent;
            const roomName = screeningInfo.children[0].children[1].querySelector('div').textContent;
            const screeningTime = screeningInfo.children[0].children[2].querySelector('div').textContent;
            
            document.getElementById('confirmTable').innerHTML = `
                <div style="display: flex; justify-content: space-between; margin-bottom: 10px;">
                    <span>影片：</span>
                    <span style="font-weight: bold;">${movieTitle}</span>
                </div>
                <div style="display: flex; justify-content: space-between; margin-bottom: 10px;">
                    <span>场次：</span>
                    <span>${screeningTime}</span>
                </div>
                <div style="display: flex; justify-content: space-between; margin-bottom: 10px;">
                    <span>放映厅：</span>
                    <span>${roomName}</span>
                </div>
                <div style="display: flex; justify-content: space-between; margin-bottom: 10px;">
                    <span>座位：</span>
                    <span>${seatNames}</span>
                </div>
                <div style="display: flex; justify-content: space-between; margin-bottom: 10px;">
                    <span>票型：</span>
                    <span>${ticketTypeName}</span>
                </div>
                <hr style="border-color: #e1e5e9;">
                <div style="display: flex; justify-content: space-between; font-weight: bold; color: #28a745; font-size: 18px;">
                    <span>总金额：</span>
                    <span>¥${totalAmount}</span>
                </div>
            `;
            
            document.getElementById('purchaseModal').style.display = 'block';
        }
        
        // 显示提示信息
        function showAlert(message, type) {
            const alertDiv = document.createElement('div');
            alertDiv.className = `alert alert-${type === 'warning' ? 'warning' : (type === 'success' ? 'success' : 'danger')} alert-dismissible fade show`;
            alertDiv.innerHTML = `
                <i class="fas fa-${type === 'warning' ? 'exclamation-triangle' : (type === 'success' ? 'check-circle' : 'exclamation-triangle')} me-2"></i>
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            `;
            
            const container = document.querySelector('.container');
            container.insertBefore(alertDiv, container.firstChild.nextSibling);
            
            // 自动消失
            setTimeout(() => {
                if (alertDiv.parentNode) {
                    alertDiv.remove();
                }
            }, 5000);
        }
        
        // 处理购买
        function processPurchase() {
            const screeningId = document.getElementById('screeningSelect').value;
            const isChildTicket = document.querySelector('input[name="ticketType"]:checked').value === 'true';
            const discount = parseFloat(document.getElementById('discountInput').value);
            const seatNumbers = selectedSeats.join(',');
            
            // 显示加载状态
            const purchaseBtn = document.querySelector('#purchaseModal .btn-success');
            const originalText = purchaseBtn.textContent;
            purchaseBtn.disabled = true;
            purchaseBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>处理中...';
            
            // 创建表单数据
            const formData = new FormData();
            formData.append('screeningId', screeningId);
            formData.append('seatNumbers', seatNumbers);
            formData.append('isChildTicket', isChildTicket ? 'true' : 'false');
            formData.append('discount', discount);
            
            fetch('/receptionist/sell-ticket', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // 关闭确认模态框
                    closeModal('purchaseModal');
                    
                    // 显示成功模态框
                    showSuccessModal(data.order);
                    
                    // 刷新座位图
                    loadSeatMap();
                } else {
                    showAlert(data.message || '购票失败，请重试', 'error');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showAlert('购票失败，请重试', 'error');
            })
            .finally(() => {
                // 恢复按钮状态
                purchaseBtn.disabled = false;
                purchaseBtn.innerHTML = originalText;
            });
        }
        
        // 显示购买成功模态框
        function showSuccessModal(orderData) {
            // 填充成功信息
            document.getElementById('successOrderId').textContent = orderData.orderId;
            document.getElementById('successMovieTitle').textContent = currentScreening.movie.title;
            document.getElementById('successScreeningTime').textContent = new Date(currentScreening.startTime).toLocaleString('zh-CN');
            document.getElementById('successSeats').textContent = (orderData.seats && Array.isArray(orderData.seats)) ? orderData.seats.join(', ') : '';
            document.getElementById('successTotalAmount').textContent = '¥' + document.getElementById('totalAmount').textContent;
        
            // 显示电子票号
            if (orderData.ticketNumbers && Array.isArray(orderData.ticketNumbers) && orderData.ticketNumbers.length > 0) {
                document.getElementById('successTicketNumbers').textContent = orderData.ticketNumbers.join(', ');
                document.getElementById('ticketNumbersContainer').style.display = 'flex';
            } else {
                document.getElementById('ticketNumbersContainer').style.display = 'none';
            }
        
            // 显示成功模态框
            document.getElementById('successModal').style.display = 'block';
        }
        
        
        
        // 关闭模态框
        function closeModal(modalId) {
            document.getElementById(modalId).style.display = 'none';
        }
        
        // 重置表单
        function resetForm() {
            selectedSeats = [];
            document.getElementById('movieSelect').value = '';
            document.getElementById('screeningSelect').innerHTML = '<option value="">请先选择影片</option>';
            document.getElementById('screeningSelect').disabled = true;
            document.getElementById('loadSeatsBtn').disabled = true;
            document.getElementById('ticketingInterface').style.display = 'none';
            
            // 重置票型选择
            document.querySelector('input[name="ticketType"][value="false"]').checked = true;
            document.getElementById('discountInput').value = '1.0';
            
            updateSelectedSeatsDisplay();
            updatePricing();
        }
    </script>
</body>
</html>